package com.googlecode.pacswitch;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author Andrey Pavlenko
 */
public class CloseOnCompleteHandler implements
        CompletionHandler<Integer, Object> {
    private final AsynchronousSocketChannel _clientSocket;
    private final PacSwitch _ps;

    public CloseOnCompleteHandler(final PacSwitch ps,
            final AsynchronousSocketChannel clientSocket) {
        _ps = ps;
        _clientSocket = clientSocket;
    }

    @Override
    public void completed(final Integer result, final Object attachment) {
        try {
            _clientSocket.close();
        } catch (final IOException ex) {
            _ps.getConfig().getLog().error("Error occurred", ex);
        }
    }

    @Override
    public void failed(final Throwable exc, final Object attachment) {
        try {
            _ps.getConfig().getLog().error("Error occurred", exc);

            if (_clientSocket.isOpen()) {
                _clientSocket.close();
            }
        } catch (final IOException ex) {
            _ps.getConfig().getLog().error("Error occurred", ex);
        }
    }
}
